<?php
/**
 * 对接金蝶库存基础服务
 * Created by PhpStorm.
 * User: Min
 * Date: 2018/4/2
 * Time: 10:04
 */

namespace SDXApi\Service\Kingdee;
use Think\Model;

class KingdeeService
{
    /**
     * 金蝶域名
     * @var string
     */
    protected $host = 'http://ts.shidexian.com/warehousemange/';

    /**
     * 查询商品可用库存
     * @var string
     */

    protected $stockUrl = 'getgoodswarehouse';

    /**
     * 查询商品可用库存 ,不返回明细
     */
    protected $stockSingle = 'checkgoodsusablewarehouse';

    /** 提交占用订单商品库存请求
     * @var string
     */
    protected $submitOrder='submitordergoodsinventoryrequest';

    /**生成订单自动取消
     * @var string
     */
    protected $autoOrderCancel='autoordercancel';

    /**
     * 根据商品货号和对应所属仓库ID查询商品可用库存
     * @author Min
     * @param $wid
     * @param $goods_sn
     * @return mixed
     */
    public function getGoodsStockByGoodsSn($wid, $goods_sn)
    {

        $param = array(
            'wid' => $wid,
            'goods' => is_array($goods_sn) ? $goods_sn : array($goods_sn)
        );


        if(!empty($param['goods'])){
            $goodsList=M("goods")->where(array("goods_sn"=>array("in",$param['goods'])))->field('supplier_code as k3_supplier_sn,consignment as k3_vmi,goods_sn')->select();
            $goodsParam=array();
            foreach($goodsList as $goods){
                if(in_array($goods['goods_sn'],$param['goods'])){
                    $goodsParamTemp=array();
                    $goodsParamTemp['goods_sn']=$goods['goods_sn'];
                    $goodsParamTemp['k3_vmi']=(int)$goods['k3_vmi'];
                    $goodsParamTemp['k3_supplier_sn']=$goods['k3_supplier_sn'];
                    $goodsParam[$goods['goods_sn']]=$goodsParamTemp;
                }

            }
            $paramG=array(
                'wid' => $wid,
                'goods'=>$goodsParam
            );
        }

        $result = $this->postToKingdee($this->stockSingle, array('goodsdata' => json_encode($paramG)));



        $data = array();
        if (!is_array($goods_sn)) {
//print_r(json_encode($param));exit;
            $data[$goods_sn] = $result['data'][$goods_sn] ? (int)$result['data'][$goods_sn] : 0;

        } else {
            foreach ($goods_sn as $key=>$val) {
                $stock =  $result['data'][$val];
                $data[$val] = $stock ? (int)$stock : 0;
            }

        }




        return array(
            'data' => $data,
            'code' => 200
        );

    }

    /**
     * @role 提交占用订单商品库存请求
     * @author Jianhe
     * @param $order_id
     * @param $order
     * @param $cart_goods
     * @return mixed
     */
    public function submitOrderGoodsInventoryRequest($order_id,$order,$cart_goods){
        $orderData=array(
            "order_id"=>$order_id,
            "order_sn"=>$order['order_sn'],
            "wid"=>$order['wid'],
            "freight"=>$order['shipping_fee'],
            "discountamount"=>$order['discount']+$order['bonus']
        );
        $GoodsData=array();
        foreach($cart_goods as $goods){
            $goodsItem=array();
            $goodsItem['goods_id']=$goods['goods_id'];
            $goodsItem['goods_sn']=$goods['goods_sn'];
            $goodsItem['goods_number']=$goods['goods_number'];
            $goodsItem['goods_price']=$goods['goods_price']-$goods['bonus_price']-$goods['discount_price'];
            $goodsItem['spec_unit']=$goods['spec_unit'];
            $goodsItem['k3_supplier_sn']=isset($goods['supplier_code'])?$goods['supplier_code']:"";
            $goodsItem['k3_vmi']=isset($goods['consignment'])?$goods['consignment']:"";
            $goodsItem['best_time']=$goods['best_time'];
            $goodsItem['giving']=$goods['giving'];
            $GoodsData[]=$goodsItem;
        }
        $orderData['GoodsData']=$GoodsData;

        $result=$this->postToKingdee($this->submitOrder, array('orderdata' => json_encode($orderData)));
        if($result['code']!=200){
            var_dump(json_encode($orderData));
            var_dump($result);
            exit();
        }
        return $result;
    }

    /**
     * @role 生成订单自动取消
     * @author Jianhe
     * @param $order_id
     * @return mixed
     */
    public function autoOrderCancel($order_id){
        return $this->postToKingdee($this->autoOrderCancel, array('order_id' => $order_id));
    }

    /**
     * @role 查询商品库存数，不返回详细信息
     * @author chenxx
     * @param $wid int 仓库id
     * @param $goods_sn string|array 商品货号
     * @return array 商品库存 key=>商品货号 value=>库存数量
     */
    public function checkStockSingle($wid,$goods_sn){
        $param = array(
            'wid' => $wid,
            'goods' => is_array($goods_sn) ? $goods_sn : array($goods_sn)
        );


        if(!empty($param['goods'])){
            $goodsList=M("goods")->where(array("goods_sn"=>array("in",$param['goods'])))->field('supplier_code as k3_supplier_sn,consignment as k3_vmi,goods_sn')->select();
            $goodsParam=array();
            foreach($goodsList as $goods){
                if(in_array($goods['goods_sn'],$param['goods'])){
                    $goodsParam[$goods['goods_sn']]=$goods;
                }

            }
            $param['goods']=$goodsParam;
        }
        $result = $this->postToKingdee($this->stockSingle, array('goodsdata' => json_encode($param)));
        if($result['status'] == 'error'){
            returnApiError('条码错误，请扫描商品上其他条码');
        }
        $data = array();
        if (!is_array($goods_sn)) {
            $data[$goods_sn] = $result['data'][$goods_sn]? $result['data'][$goods_sn] : array($goods_sn => 0);

        } else {
            foreach ($goods_sn as $key=>$val) {
                $data[$val] = isset($result['data'][$val]) ? $result['data'][$val] : 0;
            }
        }
        return $data;
    }

    /**
     * @author Min
     * @param $url
     * @param $param
     * @return mixed
     */
    protected function postToKingdee($url, $param)
    {
        $data_json = $this->http_post($this->host.$url, $param);
        $result = json_decode($data_json, true);

        if(! in_array($result['code'], array(200, 400))) {
            write_log(json_encode(array('kingdee' => $data_json)), 'KingdeeServiceError');

            returnApiError('金蝶接口异常', array('error' => $data_json));
        }
        return $result;
    }

    /**
     * @author Min
     * @param $url
     * @param $param
     * @return bool|mixed
     */
    private function http_post($url, $param){
        $post_file=false;
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        //$aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        return $sContent;
    }

}